const userService = require('../services/user.service');
const UserService = require('../services/user.service')

class Controller {
    async create(ctx, next)
    {
       //获取用户信息
        const user = ctx.request.body;
       
        //获取到用户信息时开始验证一下是否合法
        const { name, password } = user;
        if (!name || !password)
        {
            ctx.body = {
                code: 1002,
                message:"name or password is empty"
            }  
            return; 
        }

        //查看是否存在相同的用户名
        let val = await UserService.findName(user.name);
        if (val.length) {
            ctx.body = {
                code:1002,
                message: "user name is exist"
            }

            return;
        } 

       //保存到数据库
        val = await UserService.create(user);   
        //返回创建成功的消息到前端
        ctx.body = {
            message: val,
            code:1001
        }

        await next();
    }
}

module.exports = new Controller();